package com.java.simple.smallspring.core.convert.support;

import com.java.simple.smallspring.core.convert.converter.Converter;
import com.java.simple.smallspring.core.convert.converter.ConverterFactory;
import com.java.simple.smallspring.util.NumberUtils;
import com.sun.istack.internal.Nullable;
import lombok.RequiredArgsConstructor;

/**
 * @author zhoujunlin
 * @date 2022年11月19日 15:03
 * @desc
 */
public class StringToNumberConverterFactory implements ConverterFactory<String, Number> {

    @RequiredArgsConstructor
    private static final class StringToNumber<T extends Number> implements Converter<String, T> {
        private final Class<T> targetType;

        @Override
        @Nullable
        public T convert(String source) {
            if (source.isEmpty()) {
                return null;
            }
            return NumberUtils.parseNumber(source, this.targetType);
        }
    }

    @Override
    public <T extends Number> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToNumber<>(targetType);
    }
}
